package com.hontech.bv.ui.window

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.hontech.bv.R
import com.hontech.bv.app.AppContext
import com.hontech.bv.task.appScope
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.AutoHideKeyActivity
import com.hontech.bv.utils.dimenIntById
import com.hontech.bv.utils.toInt
import kotlinx.coroutines.launch

private class FormLine(
    val view: View,
    val tvName: TextView,
    val etVal: EditText
)

class FormKV(val name: String, val value: String)

private fun createFormLine(kv: FormKV): FormLine {
    val view = LayoutInflater.from(AppContext).inflate(R.layout.form_line, null)
    val tv = view.findViewById<TextView>(R.id.id_form_line_tv_name)
    tv.text = kv.name
    val et = view.findViewById<EditText>(R.id.id_form_line_et)
    et.setText(kv.value)
    return FormLine(view, tv, et)
}

private val width = dimenIntById(R.dimen.w650)

class FormDialog(title: String, commitText: String, kvs: Array<FormKV>, val cb: suspend (input: List<Int>) -> Unit) : MoveableWindow(R.layout.dialog_n_form, width, LayoutParams.WRAP_CONTENT, true) {

    private val btnClose = view.findViewById<Button>(R.id.id_nform_btn_close)
    private val tvTitle = view.findViewById<TextView>(R.id.id_nform_tv_title)
    private val childs = kvs.map { createFormLine(it) }
    private val btnCommit = view.findViewById<Button>(R.id.id_nform_btn_commit)

    init {
        tvTitle.text = title
        val layout = view.findViewById<LinearLayout>(R.id.id_nform_linear)
        for (child in childs) {
            layout.addView(child.view)
        }
        btnClose.setOnClickListener { dismiss() }
        btnCommit.setOnClickListener {
            try {
                val input = childs.map { it.etVal.toInt() }
                appScope.launch { cb(input) }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        btnCommit.text = commitText
    }

    fun show() {
        window.showAtLocation(AutoHideKeyActivity.parentView(), Gravity.CENTER, 0, 0)
    }
}














